package com.wondersgroup.fjzlpt.org.service.impl.timer;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.quick.framework.boot.repository.sql.bean.SQLBean;
import com.quick.framework.boot.repository.sql.bean.table.TableBean;
import com.quick.framework.boot.service.impl.OperationServiceImpl;
import com.quick.framework.util.FormatDate;
import com.quick.framework.util.IdCardUtils;
import com.wondersgroup.fjzlpt.org.dao.inter.timer.JtqyDataImprotDAO;
import com.wondersgroup.fjzlpt.org.service.inter.timer.JtqyDataImportService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * 家庭签约信息数据导入实现
 * <p>
 * <p>
 * Created by sanma on 2018/5/16.
 */
@Service
public class JtqyDataImportServiceimpl extends OperationServiceImpl implements JtqyDataImportService {

    private StringBuffer rqfldmBuf = new StringBuffer();
    @Autowired
    private JtqyDataImprotDAO jtqyDataImprotDAO;

    @Autowired
    @Qualifier("TB_JTQY_JMXX")
    private TableBean jmxxTableBean;

    @Autowired
    @Qualifier("TB_JTQY_JMRQFLGX")
    private TableBean rqflTableBean;

    @Autowired
    @Qualifier("TB_JTQY_QYXX")
    private TableBean qyxxTableBean;

    @Autowired
    @Qualifier("TB_JTQY_FWBGX")
    private TableBean fwbTableBean;

    @Autowired
    @Qualifier("TB_JTQY_QYSJB")
    private TableBean qysjTableBean;

    @Autowired
    @Qualifier("TB_JTQY_YBFWXGX")
    private TableBean ybfwxgxTableBean;

    @Value("${service.drjmxx.count}")
    private String count;

    //@Autowired
    //private IMongoOperator mongoOperator;

    @Override
    protected void insert(Map map) {

    }

    @Override
    protected void update(Map map) {
        StringBuffer sb = new StringBuffer("update DR_JTQY_JMQYXX set zt = ? , bz = ? where qyxxid = ? ");
        SQLBean sqlBean = new SQLBean(sb.toString(), new Object[]{map.get("ZT"), map.get("BZ"), map.get("QYXXID")});
        jtqyDataImprotDAO.execute(sqlBean);
    }

    @Override
    protected void delete(Map map) {

    }

    @Override
    public void importJmQyxx(JSONObject item) {
        if (isExistQyxx(item)) {
            executeImportData(item);
            this.update(item);
        }else{
            this.update(item);
        }
    }

    /**
     * 查询需要导入的居民签约数据。
     *
     * @param map
     * @return
     */
    @Override
    public JSONArray queryList(Map map) {
        int rows = 100;
        if (!StringUtils.isEmpty(count)) {
            rows = Integer.parseInt(count);
        }
        SQLBean sqlBean = new SQLBean();
        StringBuffer sb = new StringBuffer("select * from DR_JTQY_JMQYXX where zt = '01' and rownum <= ? ");
        sqlBean.setSql(sb.toString());
        sqlBean.setParamAry(new Object[]{rows});
        return jtqyDataImprotDAO.queryList(sqlBean);
    }

    private void insertJmQyxxData(JSONObject data) {
        //插入居民信息与人群分类信息（系统中有居民信息的则不更新）
        insertJmxxAndRqfl(data);
        //插入签约信息与服务包
        insertQyxxAndFwbxx(data);
        //插入医保服务项关系
        insertYbfwxGx(data);
        //插入协议

        //插入签约事件信息
        insertQysjxx(data);
        setQyxxMsg(data, "导入成功！", "02");
    }

    private boolean isExistQyxx(JSONObject data) {
        String zjhm = data.getString("ZJHM");
        String zjlx = data.getString("ZJLX");
        String zjhm_new = null;
        if ("01".equals(zjlx)) {
            if (IdCardUtils.isIDCard(zjhm)) {
                zjhm_new = IdCardUtils.get18IcOr15Ic(zjhm);
            } else {
                setQyxxMsg(data, "居民身份证格式有误，请核实！", "03");
                return false;
            }
        }
        List<Object> list = new ArrayList<>();
        list.add(zjlx);
        list.add(zjhm);
        StringBuffer sb = new StringBuffer("select xzqhmc , yljgmc , tdmc , qyys , fwbmc , qysj , qyxxid ");
        sb.append("from V_JTQY_QYXX where ZJLX = ? and (QYLX = '01' OR QYLX = '02' OR QYLX = '00' OR QYLX = '07') ");
        if (StringUtils.isEmpty(zjhm_new)) {
            sb.append("and ZJHM = ? ");
        } else {
            sb.append("and (ZJHM = ? OR ZJHM = ?) ");
            list.add(zjhm_new);
        }
        SQLBean sqlBean = new SQLBean(sb.toString(), list.toArray());
        JSONObject result = jtqyDataImprotDAO.queryOne(sqlBean);
        if (!result.isEmpty()) {
            StringBuffer msg = new StringBuffer("该居民于").append(result.get("QYSJ"))
                    .append("在").append(result.get("XZQHMC")).append("的")
                    .append(result.get("YLJGMC")).append("下的").append(result.get("TDMC"))
                    .append("中的").append(result.getString("QYYS")).append("医生").append("签约了").append(result.get("FWBMC"))
                    .append(" 签约记录ID [ " + result.get("QYXXID") + " ]");
            //data.put("BZ" , msg.toString());
            //data.put("ZT" , "03");
            setQyxxMsg(data, msg.toString(), "04");
        }
        return result.isEmpty();
    }

    private void executeImportData(JSONObject data) {
        String ptjgid, tdid, userid, jmxxid, fwbid;
        String zjhm = data.getString("ZJHM");
        if (IdCardUtils.isIDCard(zjhm)) {
            ptjgid = getPtjgid(data);
            if (StringUtils.isEmpty(ptjgid)) {
                setQyxxMsg(data, "未找到该医疗机构代码所对应的机构，请先在家签系统中维护好机构与人员信息，或者核对医疗机构代码是否正确", "");
            } else {
                fwbid = getFwbid(data, ptjgid);
                if (!StringUtils.isEmpty(fwbid)) {
                    //setQyxxMsg(data , "未找到服务包信息，请先在家签系统中维护好服务包信息，或者核对服务包编码是否正确");
                    userid = getUserid(data);
                    if (StringUtils.isEmpty(userid)) {
                        setQyxxMsg(data, "系统总未找到签约医生信息，请先在家签系统中维护该医生信息，或者核实医生信息是否有误。", "");
                    } else {
                        tdid = getTdid(data, userid, ptjgid);
                        if(!checkRqfl(data)){
                            setQyxxMsg(data, "人群分类代码不正确，请确认!", "");
                        }else if (!StringUtils.isEmpty(tdid)) {
                            jmxxid = getJmxxid(data);
                            data.put("PTJGID", ptjgid);
                            data.put("USERID", userid);
                            data.put("TDID", tdid);
                            data.put("JMXXID", jmxxid);
                            data.put("FWBID", fwbid);
                            this.insertJmQyxxData(data);
                        }
                    }
                }
            }
        }else{
            setQyxxMsg(data, "居民证件号码格式有误，请核对信息。", "");
        }
    }

    /**
     * 验证人群分类
     * @param data
     * @return
     */
    private boolean checkRqfl(JSONObject data){
        boolean isSuccess = true;
        String rqfldm = data.getString("RQFLDM");
        if (!StringUtils.isEmpty(rqfldm)) {
            if(rqfldmBuf.length()==0){
                SQLBean rqflBean = new SQLBean("select * from TB_ZY_RQFL where JLZT='1'");
                JSONArray rqflArr = jtqyDataImprotDAO.queryList(rqflBean);
                for(int i=0;i<rqflArr.size();i++){
                    rqfldmBuf.append(rqflArr.getJSONObject(i).getString("XMDM")+",");
                }
            }
            String[] rqflAry = rqfldm.split(",");
            for (String value : rqflAry) {
                if(rqfldmBuf.indexOf(value) == -1){
                    isSuccess = false;
                    break;
                }
            }
        }
        return isSuccess;
    }

    private String getFwbid(JSONObject data, String ptjgid) {
        String msg = "";
        SQLBean sqlBean = new SQLBean("select FWBID , sfbhybfwx from tb_xxwh_fwbjbxx where fwbid = ? AND FWBZT = '1' ");
        sqlBean.setParamAry(new Object[]{data.getString("QYFWB")});
        JSONObject result = jtqyDataImprotDAO.queryOne(sqlBean);
        if (!result.isEmpty()) {
            String ybfwx = result.getString("SFBHYBFWX");
            if ("1".equals(ybfwx)) {
                String ybfw = data.getString("YBFWX");
                String ybfw_cs = data.getString("YBFWXCS");
                if (StringUtils.isEmpty(ybfw) && StringUtils.isEmpty(ybfw_cs)) {
                    setQyxxMsg(data, "服务包包含医保服务项，请提供医保服务项信息。", "");
                    return msg;
                } else {
                    String[] ybfwAry = ybfw.split("\\|");
                    String[] ybfwcsAry = ybfw_cs.split("\\|");
                    if (ybfwAry.length != ybfwcsAry.length) {
                        setQyxxMsg(data, "医保服务项信息与医保服务项次数不匹配。", "");
                        return msg;
                    } else {
                        JSONArray ybfwxxx = new JSONArray();
                        for (int i = 0; i < ybfwAry.length; i++) {
                            if (StringUtils.isNumeric(ybfwcsAry[i])) {
                                SQLBean fwxx = new SQLBean("select fwid , sfbz dj from tb_xxwh_fwxx where yljgid = ? and fwid = ? and fwlb = '04' ");
                                fwxx.setParamAry(new Object[]{ptjgid, ybfwAry[i]});
                                JSONObject item = jtqyDataImprotDAO.queryOne(fwxx);
                                if (item.isEmpty()) {
                                    setQyxxMsg(data, "系统中未找到医保服务项信息，请先在家签系统中维护该医保服务项信息，或者核实医保服务项信息是否有误。", "");
                                    return msg;
                                } else {
                                    item.put("QYXXID", data.getString("QYXXID"));
                                    item.put("FWCS", ybfwcsAry[i]);
                                    BigDecimal dj = new BigDecimal(item.getString("dj"));
                                    BigDecimal cs = new BigDecimal(item.getString(ybfwcsAry[i]));
                                    BigDecimal zj = dj.multiply(cs);
                                    item.put("ZJ", zj.toString());
                                    ybfwxxx.add(item);
                                }
                                data.put("YBFWXXX", ybfwxxx);
                                msg = result.getString("FWBID");
                            } else {
                                setQyxxMsg(data, "医保服务项次数信息格式不对，请核实信息是否填写有误。", "");
                                return msg;
                            }

                        }
                    }
                }
            } else {
                msg = result.getString("FWBID");
            }
        } else {
            setQyxxMsg(data, "系统中未找到对应的服务包ID，请核实信息是否有误。", "");
        }
        return msg;
    }

    private String getTdid(JSONObject data, String userId, String ptjgid) {
        String tdid = "";
        List params = new ArrayList<Object>();
        params.add(userId);
        params.add(ptjgid);
        StringBuffer sql = new StringBuffer("select tdmc , tdid from tb_tdgl_tdjbxx a where a.tdid in (select tdid from tb_tdgl_tdry b ")
                .append("where b.userid = ? group by b.tdid ) and yljgid = ? and tdzt = '1' ");
        SQLBean sqlBean = new SQLBean(sql.toString(), params.toArray());
        JSONArray result = jtqyDataImprotDAO.queryList(sqlBean);
        if (!result.isEmpty() && result.size() > 0) {
            if (result.size() == 1) {
                tdid = result.getJSONObject(0).getString("TDID");
                data.put("TDMC", result.getJSONObject(0).getString("TDMC"));
            } else {
                if (!StringUtils.isEmpty(data.getString("TDMC"))) {
                    sql.append("and tdmc = ? ");
                    params.add(data.get("TDMC"));
                    SQLBean sqlBean_New = new SQLBean(sql.toString(), params.toArray());
                    JSONArray result_new = jtqyDataImprotDAO.queryList(sqlBean_New);
                    if (!result_new.isEmpty() && result_new.size() == 1) {
                        tdid = result_new.getJSONObject(0).getString("TDID");
                        data.put("TDMC", result_new.getJSONObject(0).getString("TDMC"));
                    } else {
                        String errMsg = getTdErrMsg(result);//参数为result而不是result_new(解释: result_new中的团队名称全部一样, 达不到提示要求)
                        setQyxxMsg(data, errMsg, "");
                    }
                }
                String errMsg = getTdErrMsg(result);
                setQyxxMsg(data, errMsg, "");
            }
        } else {
            setQyxxMsg(data, "该签约医生未查询到团队信息，请先维护医生与团队关系，或者核对医生信息是否有误。", "");
        }
        return tdid;
    }

    private String getTdErrMsg(JSONArray result) {
        StringBuffer sb = new StringBuffer("该医生存在多个团队，无法对应，请在以下团队中选择一条并更新至团队名称一栏中 ： ");
        for (int i = 0; i < result.size(); i++) {
            String tdmc = result.getJSONObject(i).getString("TDMC");
            sb.append(i + 1 + " - " + tdmc + " , ");
        }
        return sb.toString();
    }

    private void setQyxxMsg(JSONObject data, String msg, String zt) {
        if (StringUtils.isEmpty(zt)) {
            zt = "03";
        }
        data.put("BZ", msg);
        data.put("ZT", zt);
    }

    private String getUserid(JSONObject data) {
        String userid = "";
        SQLBean sqlBean = new SQLBean("select userid , xm from tb_zd_yljgryxx where yljgdm = ? and sfzh = ? ");
        sqlBean.setParamAry(new Object[]{data.getString("YLJGDM"), data.getString("QYYSSFZH")});
        JSONObject result = jtqyDataImprotDAO.queryOne(sqlBean);
        if (!result.isEmpty()) {
            userid = result.getString("USERID");
            data.put("YSXM", result.getString("XM"));
        } else {
            SQLBean qyysSqlBean = new SQLBean("select userid , xm from tb_zd_yljgryxx where yljgdm = ? and xm = ? ");
            qyysSqlBean.setParamAry(new Object[]{data.getString("YLJGDM"), data.getString("QYYS")});
            result = jtqyDataImprotDAO.queryOne(qyysSqlBean);
            if (!result.isEmpty()) {
                userid = result.getString("USERID");
                data.put("YSXM", result.getString("XM"));
            }
        }
        return userid;
    }

    private String getPtjgid(JSONObject data) {
        String ptjgid = "";
        SQLBean sqlBean = new SQLBean("select ptjgid , yljgmc from tb_zd_yljgxx where yljgdm = ? ", data.getString("YLJGDM"));
        JSONObject result = jtqyDataImprotDAO.queryOne(sqlBean);
        if (!result.isEmpty()) {
            ptjgid = result.getString("PTJGID");
            data.put("YLJGMC", result.getString("YLJGMC"));
        }
        return ptjgid;
    }

    private String getJmxxid(JSONObject data) {
        String jmxxid = "";
        SQLBean sqlBean = new SQLBean("select jmxxid from tb_jtqy_jmxx where zjlx = ? and zjhm = ? ");
        sqlBean.setParamAry(new Object[]{data.getString("ZJLX"), data.getString("ZJHM")});
        JSONObject result = jtqyDataImprotDAO.queryOne(sqlBean);
        if (!result.isEmpty()) {
            jmxxid = result.getString("JMXXID");
        }
        return jmxxid;
    }

    private void insertJmxxAndRqfl(Map map) {
        String jmxxid = (String) map.get("JMXXID");
        if (StringUtils.isEmpty(jmxxid)) {
            String xb = (String) map.get("XB");
            if(xb.equals("1") || xb.equals("2")){

            }else if (xb.equals("男")) {
                xb = "1";
            }else if (xb.equals("女")) {
                xb = "2";
            }else{
                xb = "";
            }
            map.put("XB", xb);
            jmxxid = UUID.randomUUID().toString();
            map.put("JMXXID", jmxxid);
            if(!StringUtils.isEmpty((String)map.get("CSRQ"))){
                map.put("CSRQ" , FormatDate.getDateY_M_D((String)map.get("CSRQ")));
            }
            map.put("ZJHM", IdCardUtils.get18Ic((String)map.get("ZJHM")));
            SQLBean jmxxInsert = jmxxTableBean.getInsertSQLBean(map);
            jtqyDataImprotDAO.execute(jmxxInsert);
            String rqfldm = (String) map.get("RQFLDM");
            if (!StringUtils.isEmpty(rqfldm)) {
                String[] rqflAry = rqfldm.split(",");
                List<Map<String, String>> list = new ArrayList<>();
                for (String value : rqflAry) {
                    if (value.length() == 1) {
                        value = "0" + value;
                    }
                    Map<String, String> rqflMap = new HashMap<>();
                    rqflMap.put("JMXXID", jmxxid);
                    rqflMap.put("RQFLID", value);
                    list.add(rqflMap);
                }
                SQLBean rqflInsert = rqflTableBean.getInsertBatchSQLBean(list);
                jtqyDataImprotDAO.execute(rqflInsert);
            }
        }
    }

    private void insertQyxxAndFwbxx(Map map) {
        Map qyxxMap = map;
        qyxxMap.put("QYSJ", FormatDate.getDateY_M_D((String) map.get("QYSJ")));
        qyxxMap.put("SXSJ", FormatDate.getDateY_M_D((String) map.get("SXSJ")));
        qyxxMap.put("JSSJ", FormatDate.getDateY_M_D((String) map.get("JSSJ")));
        qyxxMap.put("QYLX", "01");
        qyxxMap.put("SFXY", "0");
        qyxxMap.put("SFYX", "0");
        qyxxMap.put("SFBS", "0");
        qyxxMap.put("ZTMS", "后台脚本导入数据。");
        qyxxMap.put("YLTDID", map.get("TDID"));
        qyxxMap.put("YLJGID", map.get("PTJGID"));
        qyxxMap.put("USID", map.get("USERID"));
        SQLBean qyxxInsert = qyxxTableBean.getInsertSQLBean(qyxxMap);
        jtqyDataImprotDAO.execute(qyxxInsert);
        qyxxMap.put("FWBSX", "1");
        SQLBean fwbgxInsert = fwbTableBean.getInsertSQLBean(qyxxMap);
        jtqyDataImprotDAO.execute(fwbgxInsert);
    }

    private void insertQysjxx(Map map) {
        Map qysjMap = map;
        qysjMap.put("YSID", map.get("USERID"));
        qysjMap.put("XYID", map.get("XYID"));
        qysjMap.put("SJLX", "01");
        qysjMap.put("ID", UUID.randomUUID().toString());
        qysjMap.put("CZSJ", new Date());
        qysjMap.put("BZ", "后台脚本导入数据。");
        qysjMap.put("XYID", "XYID");
        SQLBean qysjInsert = qysjTableBean.getInsertSQLBean(qysjMap);
        jtqyDataImprotDAO.execute(qysjInsert);
    }

    private void insertYbfwxGx(Map map) {
        String value = (String) map.get("YBFWXXX");
        if (!StringUtils.isEmpty(value)) {
            JSONArray ybwfxxx = (JSONArray) map.get("YBFWXXX");
            if (!ybwfxxx.isEmpty() && ybwfxxx.size() > 0) {
                List<Map> list = new ArrayList<>();
                for (int i = 0; i < ybwfxxx.size(); i++) {
                    JSONObject item = ybwfxxx.getJSONObject(i);
                    list.add(item);
                    SQLBean ybfwxInsert = ybfwxgxTableBean.getInsertBatchSQLBean(list);
                    jtqyDataImprotDAO.execute(ybfwxInsert);
                }
            }
        }
    }


}
